package com.jinzhi.jzweb.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.base.CoreServiceImpl;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzapi.domain.UserDO;
import com.jinzhi.jzweb.dao.*;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.domain.param.UserQuery;
import com.jinzhi.jzweb.domain.vo.home.SysUserVo;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sys.dao.UserDao;
import com.jinzhi.wxpay.entity.OrderInfo;
import com.jinzhi.wxpay.service.OrderInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/*
 *  @author : JingChangTian
 *  @date   : 2023/7/10 15:49
 *  @description : 后台用户管理
 *
 */
@Service
public class JazSysUserServiceImpl extends CoreServiceImpl<UserDao, UserDO> implements JazSysUserService {
    /**
     * 充值记录
     */
    private final OrderInfoService orderInfoService;

    /**
     * 积分记录
     */
    private final JazUserIntegralService jazUserIntegralService;

    /**
     * 订单信息
     */
    private final JazUserOrderService jazUserOrderService;

    /**
     * 用户信息
     */
    private final UserDao userDao;

    /**
     * 月嫂信息
     */
    private final JazUserAuntService jazUserAuntService;

    /**
     * 用户需求
     */
    private final JazUserDemandService jazUserDemandService;

    /**
     * 用户评论
     */
    private final JazUserCommentService jazUserCommentService;

    private final JazGroupOrderService jazGroupOrderService;

    private final JazCoursesOrderDao jazCoursesOrderDao;

    private final JazShippingAddressService jazShippingAddressService;

    private final JazUserHouseService jazUserHouseService;

    private final JazInterviewDao jazInterviewDao;

    private final JazMessageDao jazMessageDao;

    private final JazOrderTakingDao jazOrderTakingDao;

    private final JazOrderDetailDao jazOrderDetailDao;

    private final JazUserOrderDao jazUserOrderDao;

    public JazSysUserServiceImpl(OrderInfoService orderInfoService,
                                 JazUserIntegralService jazUserIntegralService,
                                 JazUserOrderService jazUserOrderService,
                                 UserDao userDao,
                                 JazUserAuntService jazUserAuntService,
                                 JazUserDemandService jazUserDemandService,
                                 JazUserCommentService jazUserCommentService,
                                 JazGroupOrderService jazGroupOrderService,
                                 JazCoursesOrderDao jazCoursesOrderDao,
                                 JazShippingAddressService jazShippingAddressService,
                                 JazUserHouseService jazUserHouseService,
                                 JazInterviewDao jazInterviewDao,
                                 JazMessageDao jazMessageDao,
                                 JazOrderTakingDao jazOrderTakingDao,
                                 JazOrderDetailDao jazOrderDetailDao,
                                 JazUserOrderDao jazUserOrderDao) {
        this.orderInfoService = orderInfoService;
        this.jazUserIntegralService = jazUserIntegralService;
        this.jazUserOrderService = jazUserOrderService;
        this.userDao = userDao;
        this.jazUserAuntService = jazUserAuntService;
        this.jazUserDemandService = jazUserDemandService;
        this.jazUserCommentService = jazUserCommentService;
        this.jazGroupOrderService = jazGroupOrderService;
        this.jazCoursesOrderDao = jazCoursesOrderDao;
        this.jazShippingAddressService = jazShippingAddressService;
        this.jazUserHouseService = jazUserHouseService;
        this.jazInterviewDao = jazInterviewDao;
        this.jazMessageDao = jazMessageDao;
        this.jazOrderTakingDao = jazOrderTakingDao;
        this.jazOrderDetailDao = jazOrderDetailDao;
        this.jazUserOrderDao = jazUserOrderDao;
    }

    /**
     * 分页查询用户列表
     * @param userQuery
     * @return
     */
    @Override
    public Page<UserDO> getPageUser(UserQuery userQuery) {
        Page<UserDO> page = new Page<>(
                Optional.of(userQuery.getCurr()).orElse(1),
                Optional.of(userQuery.getPageSize()).orElse(10));
        Wrapper wrapper  = new EntityWrapper().
                like(StringUtil.notEmpty(userQuery.getUsername()),"nickname",userQuery.getUsername()).
                like(StringUtil.notEmpty(userQuery.getMobile()),"mobile",userQuery.getMobile())
                .orderBy("gmtCreate",false);
        List<UserDO> list = userDao.selectUserList(page,userQuery);

//        // 查询月嫂信息
//        List<JazUserAuntDO> jazUserAuntDOList = jazUserAuntService.selectList(null);
//        // 创建一个Set来存储用户ID，避免重复
//        Set<Long> auntIds = new HashSet<>();
//        for (JazUserAuntDO aunt : jazUserAuntDOList) {
//            auntIds.add(aunt.getSysUserid());
//        }
//
//        // 从阿姨列表中移除已经被计算为新增用户的阿姨
//        list.removeIf(user -> auntIds.contains(user.getId()));
        // 设置用户列表
        //page.setTotal(list.size());
        page.setRecords(list);

        return page;
    }

    @Override
    public SysUserVo getUserDetails(UserQuery userQuery) {
        SysUserVo sysUserVo = new SysUserVo();
        //获取最新充值信息、充值金额
        OrderInfo orderInfo = Optional.ofNullable(orderInfoService.selectOne(new EntityWrapper<OrderInfo>().
                eq("user_id",userQuery.getUserId()).
                eq("order_status","支付成功").
                orderBy("create_time",false))).orElse(new OrderInfo());
        sysUserVo.setRechargeMoney(Optional.ofNullable(orderInfo.getTotalFee()).orElse(new BigDecimal("0.0")));
        sysUserVo.setRechargeTime(Optional.ofNullable(orderInfo.getCreateTime()).orElse(null));
        //获取积分明细
        Page<JazUserIntegralDO> page = new Page<>(
                Optional.of(userQuery.getCurr()).orElse(1),
                Optional.of(userQuery.getPageSize()).orElse(10));
        Wrapper wrapper  = new EntityWrapper().
                eq("sys_userid",userQuery.getUserId()).
                like(StringUtil.notEmpty(userQuery.getIntegralWay()),"integral_way",userQuery.getIntegralWay()).
                orderBy("integral_time",false);
        sysUserVo.setJazUserIntegralDOs(jazUserIntegralService.selectPage(page,wrapper));
        //获取累计金额
        List<OrderInfo> orderInfoDOS =  Optional.ofNullable(orderInfoService.selectList(new EntityWrapper<OrderInfo>().
                eq("order_status","支付成功").
                eq("user_id",userQuery.getUserId()))).orElse(new ArrayList<>());
        sysUserVo.setTotalMoney(Optional.ofNullable(orderInfoDOS.stream().map(OrderInfo::getTotalFee).
                reduce(BigDecimal.ZERO,BigDecimal::add)).orElse(new BigDecimal("0.0")));
        return sysUserVo;
    }

    @Override
    @Transactional
    public Result deletedByUserId(Long id) {
        //验证有没有正在进行中的订单
        List<JazUserOrderDO> jazUserOrderDOs = jazUserOrderService.selectList(new EntityWrapper<JazUserOrderDO>().
                or("(initiate_id = {0} OR signing_id = {0})",id).
                notIn("status",2,3));
        if(!jazUserOrderDOs.isEmpty()){
            return Result.fail("有正在进行的订单无法删除");
        }
        List<JazCoursesOrderDO> jazCoursesDOS = jazCoursesOrderDao.selectList(new EntityWrapper<JazCoursesOrderDO>()
                        .eq("user_id",id)
                        .like("status","未支付"));
        if(!jazCoursesDOS.isEmpty()){
            return Result.fail("有正在进行的课程订单无法删除");
        }
        List<JazGroupOrderDO> jazGroupOrderDOS = jazGroupOrderService.selectList(new EntityWrapper<JazGroupOrderDO>()
                .eq("user_id",id)
                .like("wx_status","未支付"));
        if(!jazGroupOrderDOS.isEmpty()){
            return Result.fail("有正在进行的订单无法删除");
        }
        // 验证月嫂是否在服务期内
        List<JazUserAuntDO> jazUserAuntDOList = jazUserAuntService.selectList(new EntityWrapper<JazUserAuntDO>()
                .eq("sys_userid", id)
                .eq("signing_status", 1));
        if(!jazUserAuntDOList.isEmpty()){
            return Result.fail("有正在服务的订单无法删除");
        }
        //根据id删除用户信息
        userDao.deleteById(id);
        //根据用户id删除月嫂表信息
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("sys_userid",id);
        jazUserAuntService.delete(new EntityWrapper<JazUserAuntDO>().eq("sys_userid",id).eq("signing_status",0));
        // 删除地址信息
        jazShippingAddressService.delete(new EntityWrapper<JazShippingAddressDO>().eq("user_id",id));
        //根据用户id住宿信息
        jazUserHouseService.delete(wrapper);
        //删除用户所发布的需求
        jazUserDemandService.delete(wrapper);
        //删除用户发布的评价
        Wrapper wrapper1 = new EntityWrapper();
        wrapper.eq("comment_userid",id);
        jazUserCommentService.delete(wrapper1);
        // 删除课程订单
        jazCoursesOrderDao.delete(new EntityWrapper<JazCoursesOrderDO>().eq("user_id",id));
        // 删除团购订单
        jazGroupOrderService.delete(new EntityWrapper<JazGroupOrderDO>().eq("user_id",id));
        // 删除服务订单
        jazUserOrderService.delete(new EntityWrapper<JazUserOrderDO>().
                or("(initiate_id = {0} OR signing_id = {0})",id));
        // 删除面试邀约
        jazInterviewDao.delete(new EntityWrapper<JazInterviewDO>().
                or("(inviter_id = {0} OR invitee_id = {0})",id));
        // 删除消息
        jazMessageDao.delete(new EntityWrapper<JazMessageDO>().eq("sender_id",id).or().eq("receiver_id",id));
        // 删除收支明细
        jazOrderDetailDao.delete(new EntityWrapper<JazOrderDetailDO>().eq("user_Id",id));
        // 删除接单表
        jazOrderTakingDao.delete(new EntityWrapper<JazOrderTakingDO>().eq("inviter_id",id).or().eq("invitee_id",id));
        // 删除合同
        jazUserOrderDao.delete(new EntityWrapper<JazUserOrderDO>().eq("initiate_id",id).or().eq("signing_id",id));

        return Result.ok("删除成功");
    }

    @Override
    @Transactional
    public Boolean updateCurrentById(UserDO userDO) {
        //获取修改前当前积分
        UserDO userDO1 = userDao.selectById(userDO.getId());

        //如果积分没有变动直接return
        if(Double.parseDouble(userDO.getCurrentPoints()) == Double.parseDouble(userDO1.getCurrentPoints())){
           return true;
        }
        //积分明细
        Double integralDetail = Double.parseDouble(userDO.getCurrentPoints()) - Double.parseDouble(userDO1.getCurrentPoints());

        //新增积分记录
        JazUserIntegralDO jazUserIntegralDO = new JazUserIntegralDO();

        //如果修改的积分比修改前积分大
        if(Double.parseDouble(userDO.getCurrentPoints()) > Double.parseDouble(userDO1.getCurrentPoints())){
            //积分获取途径
            jazUserIntegralDO.setIntegralWay("系统赠送");
            //积分明细
            jazUserIntegralDO.setIntegralDetail("+" + integralDetail);
            //增加累计积分:修改积分减去修改前积分  + 修改累计积分 = 当前累计积分
            Double accumulatedPoints = Double.parseDouble(userDO.getCurrentPoints()) - Double.parseDouble(userDO1.getCurrentPoints())
                    +Double.parseDouble(userDO1.getAccumulatedPoints());
            userDO.setAccumulatedPoints(accumulatedPoints.toString());
        }else {
            //积分获取途径
            jazUserIntegralDO.setIntegralWay("系统扣减");
            //积分明细
            jazUserIntegralDO.setIntegralDetail(integralDetail.toString());
        }

        //用户Id
        jazUserIntegralDO.setSysUserid(userDO.getId());
        //当前积分
        jazUserIntegralDO.setCurrentIntegral(userDO.getCurrentPoints());
        //日期
        jazUserIntegralDO.setIntegralTime(new Date());
        jazUserIntegralService.insert(jazUserIntegralDO);
        return updateById(userDO);
    }

}
